#include<cstdio>//uncle-lu
#include<algorithm>
template<class T>void read(T &x)
{
	x=0;int f=0;char ch=getchar();
	while(ch<'0'||ch>'9') { f|=(ch=='-'); ch=getchar(); }
	while(ch<='9'&&ch>='0') { x=(x<<1)+(x<<3)+(ch^48); ch=getchar(); }
	x = f ? -x : x;
	return ;
}

struct node{
	int x,y;
	node(int xx=0,int yy=0){x = xx;y = yy;}
};
node qu[1000010];
int Map[10010][10010];
int tags[10010][10010];
int sum_tag[1000010];
int turn_x[5]={0,1,-1,0,0};
int turn_y[5]={0,0,0,1,-1};
int n,m,cnt;

void __bfs(int x,int y)
{
	int head=0,last=1,tot=1;
	node now(x,y);
	cnt++;
	qu[++head] = now;
	tags[x][y] = cnt;
	while(head>=last)
	{
		now = qu[last];
		for(int i=1;i<=4;++i)
		{
			int xx = now.x + turn_x[i], yy = now.y + turn_y[i];
			if(xx>n||xx<1||yy<1||yy>n)continue;
			if(Map[now.x][now.y]==Map[xx][yy])continue;
			if(tags[xx][yy])continue;
			tags[xx][yy] = cnt;
			tot++;
			node k(xx,yy);
			qu[++head]=k;
		}
		last++;
	}
	sum_tag[cnt] = tot;
	return ;
}

void _BFS()
{
	for(int i=1;i<=n;++i)
		for(int j=1;j<=n;++j)
			if(!tags[i][j])__bfs(i,j);
	return ;
}

int main()
{
	read(n);read(m);
	for(int i=1;i<=n;++i)
		for(int j=1;j<=n;++j)
			scanf("%1d",&Map[i][j]);

	_BFS();

	int x,y;

	for(int i=1;i<=m;++i)
	{
		read(x);read(y);
		printf("%d\n",sum_tag[tags[x][y]]);
	}

	return 0;
}
